﻿using GetMan.Core.DB.Entities;
using System;
using System.ComponentModel.Composition;

namespace GetMan.Core.DB.Services.Request
{
    [Export(typeof(IRequestService))]
    public class RequestService : BaseService<RequestEntity>, IRequestService
    {

        [ImportingConstructor]
        public RequestService(IFreeSql freeSql) : base(freeSql)
        {

        }

        public long AddOrUpdate(RequestEntity entity)
        {
            var inEntity = _freeSql.Select<RequestEntity>()
                .Where(x => x.NodeId == entity.NodeId)
                .First();
            if (inEntity != null)
            {
                inEntity.UpdateTime = DateTime.Now;
                _freeSql.Update<RequestEntity>()
                    .Set(x => x.UpdateTime, inEntity.UpdateTime)
                    .ExecuteAffrows();
                return inEntity.Id;
            }
            else
            {
                return _freeSql.Insert<RequestEntity>(entity)
                    .ExecuteIdentity();
            }
        }

        public RequestEntity GetByNodeId(long nodeId)
        {
            return _freeSql.Select<RequestEntity>()
                .Where(x => x.NodeId == nodeId)
                .First();
        }
    }
}